<template>
  <div v-if="error" class="error-boundary">
    <div class="error-content">
      <n-icon size="48" color="#ff4757">
        <WarningOutline />
      </n-icon>
      <h3>页面加载失败</h3>
      <p>{{ error.message || '组件渲染时发生错误' }}</p>
      <div class="error-actions">
        <n-button type="primary" @click="retry">
          重试
        </n-button>
        <n-button @click="goBack">
          返回
        </n-button>
      </div>
    </div>
  </div>
  <slot v-else />
</template>

<script setup lang="ts">
import { ref, onErrorCaptured } from 'vue'
import { useRouter } from 'vue-router'
import { WarningOutline } from '@vicons/ionicons5'

const router = useRouter()
const error = ref<Error | null>(null)

onErrorCaptured((err: Error) => {
  console.error('ErrorBoundary caught error:', err)
  error.value = err
  return false // 阻止错误继续传播
})

const retry = () => {
  error.value = null
  // 强制重新渲染
  window.location.reload()
}

const goBack = () => {
  router.back()
}
</script>

<style scoped>
.error-boundary {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  padding: 40px;
}

.error-content {
  text-align: center;
  max-width: 400px;
}

.error-content h3 {
  margin: 16px 0 8px;
  color: #ff4757;
}

.error-content p {
  margin-bottom: 24px;
  color: #666;
}

.error-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
}
</style> 